package com.lingnan.config;

import com.alibaba.fastjson2.JSON;
import com.lingnan.entity.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// WebSocketHandler.java
@Component
@Slf4j
public class NotificationWebSocketHandler extends TextWebSocketHandler {

    // 存储用户会话
    private static final Map<Long, WebSocketSession> USER_SESSIONS = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = getUserIdFromSession(session);
        if (userId != null) {
            USER_SESSIONS.put(Long.parseLong(userId), session);
            log.info("用户 {} WebSocket连接建立", userId);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = getUserIdFromSession(session);
        if (userId != null) {
            USER_SESSIONS.remove(Long.parseLong(userId));
            log.info("用户 {} WebSocket连接关闭", userId);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理客户端发送的消息（如心跳包）
        String payload = message.getPayload();
        log.debug("收到WebSocket消息: {}", payload);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket传输错误", exception);
        session.close();
    }

    /**
     * 向指定用户发送消息
     */
    public void sendMessageToUser(Long userId, WebSocketMessage message) {
        WebSocketSession session = USER_SESSIONS.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(JSON.toJSONString(message)));
                log.debug("向用户 {} 发送WebSocket消息", userId);
            } catch (Exception e) {
                log.error("发送WebSocket消息失败", e);
                USER_SESSIONS.remove(userId);
            }
        }
    }

    /**
     * 向所有在线用户发送消息
     */
    public void sendMessageToAll(WebSocketMessage message) {
        USER_SESSIONS.entrySet().removeIf(entry -> {
            WebSocketSession session = entry.getValue();
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(JSON.toJSONString(message)));
                    return false;
                } catch (Exception e) {
                    log.error("发送WebSocket消息失败", e);
                    return true;
                }
            }
            return true;
        });
    }

    /**
     * 获取在线用户数量
     */
    public int getOnlineUserCount() {
        return USER_SESSIONS.size();
    }

    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(Long userId) {
        WebSocketSession session = USER_SESSIONS.get(userId);
        return session != null && session.isOpen();
    }

    private String getUserIdFromSession(WebSocketSession session) {
        // 从URL参数或Token中获取用户ID
        String query = session.getUri().getQuery();
        if (query != null && query.contains("userId=")) {
            return query.split("userId=")[1].split("&")[0];
        }
        return null;
    }
}
